﻿import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:test_app/core/base/base/base_logic.dart';

import 'builder_forms_state.dart';

class BuilderFormsController extends BaseLogic {
  final BuilderFormsState uiState = BuilderFormsState();

  void handleSubmit(BuildContext context) {
    final formState = uiState.formKey.currentState;
    final passed = formState?.saveAndValidate() ?? false;
    if (passed) {
      final values = formState!.value;
      final region = values['region'] as String?;
      uiState.updateRegionLabel(region);
      TDToast.showSuccess(
        '提交成功：${values['productName'] ?? ''}',
        context: context,
      );
      debugPrint('表单结果 => $values');
    } else {
      TDToast.showWarning('请完善表单信息', context: context);
    }
  }

  void handleReset(BuildContext context) {
    uiState.formKey.currentState?.reset();
    uiState.updateRegionLabel(null);
    FocusScope.of(context).unfocus();
  }

  void openRegionPicker(BuildContext context, FormFieldState<String> field) {
    TDPicker.showMultiLinkedPicker(
      context,
      title: '配送地区',
      data: uiState.regionOptions,
      columnNum: 3,
      initialData: uiState.resolveInitialRegion(field.value),
      onConfirm: (selected) {
        final joined = selected.join(' / ');
        field.didChange(joined);
        uiState.updateRegionLabel(joined);
        Navigator.of(context).pop();
      },
      onCancel: (_) => Navigator.of(context).pop(),
    );
  }
}
